package org.devgframwork.datasync.admin.support.init.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.devgframwork.datasync.admin.support.init.AbstractInit;
import org.devgframwork.datasync.core.entity.RabbitConfig;
import org.devgframwork.datasync.core.entity.TriggerConfig;
import org.devgframwork.datasync.core.support.DataSourceMemory;
import org.devgframwork.datasync.core.support.init.AbstractQueueInit;
import org.devgframwork.datasync.core.support.init.rabbitmq.RabbitQueueInit;
import org.devgframwork.datasync.core.support.service.TriggerConfigService;
import org.devgframwork.datasync.core.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.devgframwork.datasync.admin.rabbit.service.RabbitConfigService;

import java.util.List;

@Slf4j
public class RabbitInit extends AbstractInit {

    public RabbitInit(AbstractInit nextAbstractInit) {
        super(nextAbstractInit);
    }

    @Override
    public void initComponent() {
        RabbitConfigService rabbitConfigService = DataSourceMemory.applicationContext.getBean(RabbitConfigService.class);
        QueryWrapper<RabbitConfig> rabbitConfigQueryWrapper = new QueryWrapper();
        rabbitConfigQueryWrapper.eq("IS_DELETE", 0);
        List<RabbitConfig> rabbitConfigList = rabbitConfigService.list(rabbitConfigQueryWrapper);
        if (null == rabbitConfigList || rabbitConfigList.size() <= 0) {
            log.warn("rabbitConfigList is empty");
            return;
        }
        TriggerConfigService triggerConfigService = DataSourceMemory.applicationContext.getBean(TriggerConfigService.class);
        for (RabbitConfig rabbitConfig : rabbitConfigList) {
            String connnectionName = rabbitConfig.getConnectionName();
            String host = rabbitConfig.getHost();
            Integer port = rabbitConfig.getPort();
            String virtualHost = rabbitConfig.getVirtualHost();
            if (CommonUtil.isNullOrEmpty(connnectionName)) {
                log.error("host:{},port:{},virtualHost:{} connnectionName cannot be empty", host, port, virtualHost);
                continue;
            }
            QueryWrapper<TriggerConfig> triggerConfigQueryWrapper = new QueryWrapper();
            triggerConfigQueryWrapper.eq("IS_DELETE", 0);
            triggerConfigQueryWrapper.eq("CONNECTION_NAME", connnectionName);
            List<TriggerConfig> rabbitQueueList = triggerConfigService.list(triggerConfigQueryWrapper);
            AbstractQueueInit rabbitQueue = new RabbitQueueInit();
            rabbitQueue.invoke(rabbitConfig, rabbitQueueList);
        }
        log.info("init rabbit success");
    }
}
